package com.wgj.android;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.annotation.TargetApi;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import com.jiaai.xui.cache.XCache;
import com.jiaai.xui.utils.XEmptyUtils;
import com.jiaai.xui.utils.log.XLog;
import com.jiaai.xui.view.widget.XToast;
import com.wgj.android.tools.AccessibilityServerTools;
import com.wgj.android.ui.activity.FriendsCleanActivity;
import com.wgj.android.ui.activity.LoginActivity;
import com.wgj.android.utils.AccessibilityUtil;

import java.io.IOException;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by Administrator on 2017/10/31.
 */

public class WXFriendsAccessibilityService extends AccessibilityService {
    private  static  final  String FRIEAN_INFO_PAGE="com.tencent.mm.plugin.profile.ui.ContactInfoUI";
    private  static  final  String WEIXI_CHAT_PAGE="com.tencent.mm.ui.chatting";
    private  static  final  String WEIXI_HOME_PAGE="com.tencent.mm.ui.LauncherUI";
    private static  final  String FRIEND_ITEM_ID="com.tencent.mm:id/io";
    private static  final  String FRIEND_NICKNAME_ID="com.tencent.mm:id/ir";
    private static  final  String FRIEND_LIST_VIEW_ID="com.tencent.mm:id/i9";

    private static  final  String TO_CHAT_PAGE="com.tencent.mm:id/ahq";

    private static  final  String MSG_INPUT_ID="com.tencent.mm:id/a71";

    private static  final  String  SEND_MSG_BUT_ID="com.tencent.mm:id/a77";

    private  static  final  String  MSG_ITEM_ID="com.tencent.mm:id/iy";

    private  static  final  String  CHAT_PAGE_TOP_VIEW_ID="com.tencent.mm:id/gh"; //聊天页面顶部工具栏ID

    private  static  final  String WEIXI_BACK_BUT_ID="com.tencent.mm:id/h0";

    private  static  boolean isDel=false;
    private Handler handler = new Handler();


    private  static Set<String> exclude=new HashSet<>();
    private  static Set<String>  checkFriends=new HashSet<String>();

    private  static  int sleepTime=0;
    private  static  boolean isAutoDel=false;

    private  static  boolean isOnStartDel=false;
    private  static  boolean isUpdateNickName=false;

    private  static  boolean isEnd=false;

    private  static  boolean isStop=false;

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        sleepTime= AccessibilityUtil.getSleepTime();
        isAutoDel=AccessibilityUtil.isAutoDel();
        exclude.add("微信团队");
        exclude.add("文件传输助手");
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        int eventType = event.getEventType();
        switch (eventType) {
            case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED://通知栏
                break;
            case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
            case AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED:
                 String className = event.getClassName().toString();
                 if(className.equals(WEIXI_HOME_PAGE)){//进入微信主界面
                     AccessibilityNodeInfo  friendsPage=getFriendsListView();
                     if(friendsPage==null || !friendsPage.isVisibleToUser()){
                          goFriendsPage();
                     }else {
                         cleanFriends();
                     }
                 }else if(className.indexOf(WEIXI_CHAT_PAGE)>=0){
                        if(checkIsDelYou()){
                            toSingleChatInfoUI();
                        }else {
                            onSendMesg("旺旺通服务技术开发测试，打扰勿回！系统将要闪亮上线，请大家尽情期待……");
                        }


                 }else if(className.equals(FRIEAN_INFO_PAGE)){
                         handler.postDelayed(new Runnable() {
                             @Override
                             public void run() {
                                 if(isDel &&  !isOnStartDel){//发现僵尸粉但并没有开始清理时,点击右上更多按钮弹出菜单栏
                                     showPopBottonWindwo();
                                     return;
                                 }

                                 if(isDel && isUpdateNickName){//修改完备注回到个人祥情界面,重制状态并返回到首页
                                     isDel=false;
                                     isOnStartDel=false;
                                     isUpdateNickName=false;
                                     backChatPage();
                                     return;
                                 }
                                 toChatPage();

                              }
                         },1000*sleepTime);

                }else if(className.equals("com.tencent.mm.ui.SingleChatInfoUI")){
                     onChatMsgInfoUIToContactInfoUI();
                }else if(className.equals("android.support.design.widget.c") && isDel && isOnStartDel){//底部弹出弹单事件
                        onPopBottonMenuShow();
                 }else  if(className.equals("com.tencent.mm.ui.base.i") && isDel && isOnStartDel){
                        doDel();
                 }

                 break;
        }



    }
    /**
     * 进入通讯录页面
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private  void  goFriendsPage(){
       AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
         if (nodeInfo != null ) {
             List<AccessibilityNodeInfo>  friendTabs= nodeInfo.findAccessibilityNodeInfosByText("通讯录");
             friendTabs.get(0).getParent().performAction(AccessibilityNodeInfo.ACTION_CLICK);
             cleanFriends();
         }
    }


    /**
     * 清理僵尸粉
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private  void cleanFriends(){
        Log.i("WGJ","已检测"+checkFriends.size()+"个好友");
        final AccessibilityNodeInfo friend=getNexFriend();//获取下一需要检测 的好友
        if(friend!=null){
            try {
                AccessibilityServerTools.performActionClick(friend.getParent());
            }catch (Exception e){
                cleanFriends();
            }
        }
    }

    /**
     * 获取下一个好友
     * @return
     */
    @TargetApi(Build.VERSION_CODES.N)
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private AccessibilityNodeInfo  getNexFriend(){

        List<AccessibilityNodeInfo> friendItems=getFriendsListView().findAccessibilityNodeInfosByViewId(FRIEND_ITEM_ID);
        for(AccessibilityNodeInfo nodeInfo:friendItems) {
            if (nodeInfo.getChildCount() > 0) {
                String nickName = nodeInfo.getChild(0).getText().toString();
                if (!exclude.contains(nickName) && !checkFriends.contains(nickName)) {//排除微信团队和手机助手等好友
                    checkFriends.add(nickName);
                    return nodeInfo;
                }
            }
        }
        /**
         * 检测是否已结束,并重新打开应用！
         */
       List<AccessibilityNodeInfo> notData=getRootInActiveWindow().findAccessibilityNodeInfosByViewId("com.tencent.mm:id/ahd");
       if(notData!=null && notData.size()>0&& notData.get(0).isVisibleToUser()){
           Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
           startActivity(intent);
           return null;
       }
        //说明到了当前页最底部 需要跳到下一页面并重新开始
        getFriendsListView().performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
        return getNexFriend();
    }




    /**
     * 获取通讯录列表
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private  AccessibilityNodeInfo  getFriendsListView(){
         AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo != null) {
            List<AccessibilityNodeInfo> listViews=nodeInfo.findAccessibilityNodeInfosByViewId(FRIEND_LIST_VIEW_ID);
            if(listViews!=null && listViews.size()!=0){
                return  listViews.get(0);
            }
         }else {
            return   getFriendsListView();
        }
        return null;

    }




    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
    private  void  toChatPage(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                AccessibilityNodeInfo nodeInfo=getRootInActiveWindow();
                if(nodeInfo!=null){
                    List<AccessibilityNodeInfo> msgBut=nodeInfo.findAccessibilityNodeInfosByText("发消息");
                    if(msgBut!=null && msgBut.size()!=0){
                        AccessibilityServerTools.performActionClick(msgBut.get(0));
                    }else {
                        backChatPage();
                    }
                }
            }
        },300);

    }

    /**
     * 检查是否是僵尸粉
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private boolean   checkIsDelYou(){
         AccessibilityNodeInfo nodeInfo=getRootInActiveWindow();
         if(nodeInfo!=null){
              List<AccessibilityNodeInfo> msgItems=nodeInfo.findAccessibilityNodeInfosByViewId(MSG_ITEM_ID);
              if(msgItems!=null && msgItems.size()>0){
                  for(AccessibilityNodeInfo n:msgItems){
                      String msg=n.getText()==null?"":n.getText().toString();
                      if(!XEmptyUtils.isSpace(msg) && msg.indexOf("发送朋友验证")>=0){
                          return true;
                      }
                  }
              }
          }
         return  false;
    }



    /**
     * 设置消息内容并点击发送
     * @param content
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void   onSendMesg(final String content){

                final AccessibilityNodeInfo nodeInfo=getRootInActiveWindow();
                if(nodeInfo!=null){
                    final List<AccessibilityNodeInfo> msgInputs=nodeInfo.findAccessibilityNodeInfosByViewId(MSG_INPUT_ID);
                    if(msgInputs==null || msgInputs.size()==0|| !msgInputs.get(0).isVisibleToUser()){//如果输入框是隐藏的则表示当前输入类型为语音输入 需要转到文本输入模式
                        List<AccessibilityNodeInfo> keyInput=nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/a6z");//切换到键盘按钮
                        if(keyInput!=null && keyInput.size()>0){
                            AccessibilityServerTools.performActionClick(keyInput.get(0));
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    AccessibilityNodeInfo a=nodeInfo.findAccessibilityNodeInfosByViewId(MSG_INPUT_ID).get(0);
                                    setMsgContent(a,content);
                                }
                            },500);
                        }
                    }else {
                        setMsgContent(msgInputs.get(0),content);
                    }

                }

    }

    private  void setMsgContent(final AccessibilityNodeInfo inputNodeInfo, final String content){
        handler.postDelayed(new Runnable() {
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
            @Override
            public void run() {
                AccessibilityServerTools.performActionInput(getBaseContext(),inputNodeInfo,content);
                toClickSnedBut();
            }
        },1000*sleepTime);

    }

    /**
     * 点击发送按钮
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void toClickSnedBut() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
                List<AccessibilityNodeInfo> sendButs = null;
                if (nodeInfo != null) {
                    sendButs = nodeInfo.findAccessibilityNodeInfosByViewId(SEND_MSG_BUT_ID);
                    if (sendButs == null && sendButs.size() == 0) {
                        sendButs = nodeInfo.findAccessibilityNodeInfosByText("发送");
                    }
                }
                AccessibilityServerTools.performActionClick(sendButs.get(0));
                if (checkIsDelYou()) {//检测是僵尸粉
                    showPopBottonWindwo();
                } else {//退出当前聊天界面
                    backChatPage();
                }

            }
        }, 1000 * sleepTime);
    }


    /**
     * 退出当前聊天界面
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private  void  backChatPage(){
        handler.postDelayed(new Runnable() {

            @Override
            public void run() {
                List<AccessibilityNodeInfo>  nodeInfos=getRootInActiveWindow().findAccessibilityNodeInfosByViewId(WEIXI_BACK_BUT_ID);

                if(nodeInfos!=null&& nodeInfos.size()>0){
                    AccessibilityServerTools.performActionClick(nodeInfos.get(0));
                }
            }
        },300);


    }


    /**
     * 弹出底部菜单
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void showPopBottonWindwo(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                List<AccessibilityNodeInfo> topTools=getRootInActiveWindow().findAccessibilityNodeInfosByViewId(CHAT_PAGE_TOP_VIEW_ID);
                if(topTools!=null && topTools.size()>0){
                    AccessibilityServerTools.performActionClick(topTools.get(0).getChild(2));
                    isOnStartDel=true;
                }
            }
        },800);

    }

    /**
     * 弹出底部菜单栏
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private  void onPopBottonMenuShow(){
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                AccessibilityNodeInfo nodeInfo=getRootInActiveWindow();
                if(nodeInfo!=null){
                    List<AccessibilityNodeInfo> popwondow=nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/by0");//底部弹出菜单
                    if(popwondow!=null && popwondow.size()!=0 && popwondow.get(0).isVisibleToUser()){//当底部弹出菜单不为空时
                        if(isAutoDel){//自动删除
                            if(popwondow.get(0).getChildCount()<7){
                                popwondow.get(0).performAction(AccessibilityNodeInfo.ACTION_SCROLL_FORWARD);
                            }
                            AccessibilityNodeInfo node= popwondow.get(0).getChild(6);
                            AccessibilityServerTools.performActionClick(node);
                        }else{
                            AccessibilityNodeInfo node= AccessibilityServerTools.findNodeByText(popwondow.get(0),"设置备注及标签");
                            AccessibilityServerTools.performActionClick(node);
                        }
                    }
                }
            }
        },500);

    }

    /**
     * 弹出删除询问栏
     */
    public  void doDel() {
        AccessibilityNodeInfo nodeInfo = getRootInActiveWindow();
        if (nodeInfo != null) {
            List<AccessibilityNodeInfo> delBut = nodeInfo.findAccessibilityNodeInfosByText("删除");
            if (delBut != null && delBut.size() != 0 && delBut.get(0).isVisibleToUser()) {
                for (AccessibilityNodeInfo d : delBut) {
                    if (d.getClassName().equals("android.widget.Button")) {
                        AccessibilityServerTools.performActionClick(d);
                        isDel = false;
                        isOnStartDel = false;
                        return;
                    }
                }
            }
        }
    }




    /**
     * 跳转到聊天祥情页
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private void  toSingleChatInfoUI(){
        AccessibilityNodeInfo nodeInfo=getRootInActiveWindow();
        if(nodeInfo!=null){
            List<AccessibilityNodeInfo> ns=nodeInfo.findAccessibilityNodeInfosByViewId(CHAT_PAGE_TOP_VIEW_ID);
            if(ns!=null&& ns.size()>0){
                AccessibilityServerTools.performActionClick(ns.get(0).getChild(2));
            }
        }
    }

    /**
     * 从聊天信息页面跳转到个人祥情页面
     */
    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
    private  void onChatMsgInfoUIToContactInfoUI(){
        AccessibilityNodeInfo nodeInfo=getRootInActiveWindow();
        if(nodeInfo!=null){
            List<AccessibilityNodeInfo> ns=nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/byn");//找到成员列表
            if(ns!=null&& ns.size()>0){
                isDel=true;
                AccessibilityNodeInfo  n=ns.get(0).getChild(0);
                AccessibilityServerTools.performActionClick(n);
            }
        }
    }

    @Override
    public void onInterrupt() {

    }


    public  static  void restart(Set<String> checks){
        checkFriends=checks;
        isStop=false;

    }

    @Override
    public void onDestroy() {

        XLog.i("onDestroyonDestroyonDestroyonDestroy");
        super.onDestroy();
    }

}
